package com.xydtech.ecard.flow.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xydtech.busiflw.domain.BusiflInstStep;
import com.xydtech.busiflw.domain.BusiflWaitTask;
import com.xydtech.busiflw.service.IBusiflInstStepService;
import com.xydtech.busiflw.service.IBusiflWaitTaskService;
import com.xydtech.busiflw.service.IBusinessFlowService;
import com.xydtech.common.annotation.PassToken;
import com.xydtech.common.annotation.RsaRequest;
import com.xydtech.common.core.domain.AjaxResult;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.core.domain.entity.SysUser;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.string.StringUtil;
import com.xydtech.ecard.custgroup.service.IEcardApiCustomerGroupMerchantService;
import com.xydtech.ecard.custgroup.service.IEcardApiCustomerGroupOrganizeService;
import com.xydtech.ecard.ecard.controller.EcardApiBaseController;
import com.xydtech.ecard.ecard.service.*;
import com.xydtech.ecard.flow.domain.EcardBusiFlowLink;
import com.xydtech.ecard.flow.domain.FlowInstanceInfo;
import com.xydtech.ecard.flow.service.IEcardBusiFlowLinkService;
import com.xydtech.ecard.imp.service.IEcardApiMerchantImportTaskService;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.service.IEcardApiUserService;
import com.xydtech.system.service.ISysDeptService;
import com.xydtech.system.service.ISysUserService;
import com.xydtech.workflow.domain.WflApprauthor;
import com.xydtech.workflow.domain.WflFlowdefine;
import com.xydtech.workflow.domain.WflFlowstep;
import com.xydtech.workflow.domain.WflSteppage;
import com.xydtech.workflow.service.IWflApprauthorService;
import com.xydtech.workflow.service.IWflFlowdefineService;
import com.xydtech.workflow.service.IWflFlowstepService;
import com.xydtech.workflow.service.IWflSteppageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: XydtechBusiPlat
 * @ClassName: EcardApiBusinessFlowController
 * @description:电子名片流程Controller
 * @author: yjs
 * @create: 2024-07-22 13:24
 */
@Controller
@Slf4j
@Api(tags = "电子名片-业务流程")
@RequestMapping("/ecardSaasApi/businessFlow")
public class EcardApiBusinessFlowController extends EcardApiBaseController {
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    IBusinessFlowService businessFlowService;
    @Autowired
    private IEcardApiUserService ecardApiUserService;
    @Autowired
    private IWflFlowstepService wflFlowStepService;
    @Autowired
    private IWflApprauthorService wflApprauthorService;
    @Autowired
    private IWflFlowdefineService wflFlowdefineService;
    @Autowired
    private IBusiflInstStepService busiflInstStepService;
    @Autowired
    private IWflSteppageService wflSteppageService;
    @Autowired
    private IEcardBusiFlowLinkService ecardBusiFlowLinkService;
    @Autowired
    private IBusiflWaitTaskService busiflWaitTaskService;
    @Autowired
    private IEcardApiMerchantInfoService ecardMerchantInfoService;
    @Autowired
    private IEcardApiEnterpriseInfoService ecardEnterpriseInfoService;
    @Autowired
    private IEcardApiEnterpriseLocationService enterpriseLocationService;
    @Autowired
    private IEcardApiPersonInfoService ecardPersonInfoService;
    @Autowired
    private IEcardApiPersonAreaService ecardPersonAreaService;
    @Autowired
    private IEcardApiAgricultureInfoService ecardAgricultureInfoService;
    @Autowired
    private IEcardApiMerchantImportTaskService ecardApiMerchantImportTaskService;
    @Autowired
    private IEcardApiCustomerGroupMerchantService ecardApiCustomerGroupMerchantService;
    @Autowired
    private IEcardApiCustomerGroupOrganizeService ecardApiCustomerGroupOrganizeService;

    /**
     * 1、目前流程只支持电子名片删除功能。
     * 2、流程不支持【任务并发或 任务多选并发】
     * * @description：电子名片-新建审批流程接口
     *
     * @author：yjs
     * @date：2024/7/22 13:27
     */
    @PostMapping(value = "/addApprovalProcess")
    @ApiOperation(value = "电子名片-新建审批流程接口", notes = "电子名片-新建审批流程接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel addApprovalProcess(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            JSONObject jsonObject = JSONObject.parseObject(json);
            /**
             * keyInfo内数据说明：
             * {"busiId":业务编号,"cname":客户名称,"busiType":业务类型}
             */
            //流程类型
            String flowType = jsonObject.getString("flowType");
            //业务ID
            Long busiId = jsonObject.getLong("busiId");
            //业务类型：busiType  1-商户信息，2-企业信息，3-企业楼宇（厂区），4-个人信息，5-个人网格，6.-农业主体信息
            // 7-商户信息，8-企业信息，9-个人信息，10.-新型农业主体，11-行业客户删除，12-社团组织删除
            String busiType = jsonObject.getString("busiType");
            //流程基本信息数据
            String keyInfo = jsonObject.getString("keyInfo");
            if (StringUtils.objIsNullOrEmpty(flowType) || StringUtils.objIsNullOrEmpty(busiId) || StringUtils.objIsNullOrEmpty(keyInfo)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            //法人机构信息
            SysDept secondLevelDept = deptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //获取法人机构的ID
            Long deptId = secondLevelDept.getDeptId();
            WflFlowdefine wflFlowdefine = new WflFlowdefine();
            wflFlowdefine.setDeptId(deptId);
            wflFlowdefine.setFlowType(flowType);
            List<WflFlowdefine> list = wflFlowdefineService.selectFlowdefineByFlowType(wflFlowdefine);
            if (list.size() == 0) {
                return ResponseModel.error("未配置审批流程！");
            }
            FlowInstanceInfo flowInstanceInfo = new FlowInstanceInfo();
            flowInstanceInfo.setVersionId(list.get(0).getCurreVersion());
            flowInstanceInfo.setFlowId(list.get(0).getFlowId());
            /**查询流程第一个节点信息*/
            WflFlowstep wflFlowstep = wflFlowStepService.selectWflFlowstepByVersionIdAndOrderNum(flowInstanceInfo.getVersionId(), 1L);
            if (wflFlowstep == null) {
                return ResponseModel.error("审批流程配置不完整！");
            }
            /**
             * 查询当前业务ID下同类型审批是否存在未结束的审批流
             */
            EcardBusiFlowLink ecardBusiFlowLink = new EcardBusiFlowLink();
            ecardBusiFlowLink.setBusiType(busiType);
            ecardBusiFlowLink.setBusiId(busiId);
            List<EcardBusiFlowLink> busiFlowLinks = ecardBusiFlowLinkService.getNoEndBusiFlowList(ecardBusiFlowLink);
            if (busiFlowLinks != null && busiFlowLinks.size() > 0) {
                return ResponseModel.error("已存在同类型未结束的审批流程！");
            }

            /**初始化流程*/
            String applyId = StringUtils.getApplId();
            flowInstanceInfo.setInstanceId(applyId);
            BusiflWaitTask busiflWaitTask = businessFlowService.initBusinessFlowData(wflFlowstep, flowInstanceInfo.getFlowId(), applyId, userInfo.getUserId(), deptId, keyInfo);

            /**查询当前节点审批权限*/
            List<WflApprauthor> appAuthorList = wflApprauthorService.selectWflApprauthorList(list.get(0).getCurreVersion(), wflFlowstep.getStepId());

            /**查询流程节点页面配置信息*/
            WflSteppage wflSteppage = new WflSteppage();
            wflSteppage.setVersionId(flowInstanceInfo.getVersionId());
            wflSteppage.setStepId(wflFlowstep.getStepId());
            List<WflSteppage> pageList = wflSteppageService.selectWflSteppageList(wflSteppage);

            /**
             * 保存业务流程记录
             */
            ecardBusiFlowLink.setInstanceId(applyId);
            ecardBusiFlowLink.setCreatorId(Long.valueOf(userInfo.getRegistId()));
            ecardBusiFlowLink.setCreateTime(new Date());
            ecardBusiFlowLink.setDeptId(deptId);
            ecardBusiFlowLinkService.insertEcardBusiFlowLink(ecardBusiFlowLink);

            flowInstanceInfo.setStepId(wflFlowstep.getStepId());
            flowInstanceInfo.setTaskId(busiflWaitTask.getTaskId());
            flowInstanceInfo.setPageList(pageList);
            flowInstanceInfo.setAppAuthorList(appAuthorList);
            return ResponseModel.okToJSON(flowInstanceInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseModel.error("启动业务流程失败！");
        }
    }

    /**
     * @description：电子名片-从待办任务进入流程
     * @author：yjs
     * @date：2024/7/24 13:27
     */
    @ApiOperation(value = "电子名片-任务-从待办任务进入流程", notes = "电子名片-任务-从待办任务进入流程")
    @PostMapping("/dealWithWaitTask")
    @ResponseBody
    @RsaRequest
    public ResponseModel dealWithWaitTask(@RequestBody FlowInstanceInfo flowInstanceInfo) {
        /**查询流程节点页面配置信息*/
        WflSteppage wflSteppage = new WflSteppage();
        wflSteppage.setVersionId(flowInstanceInfo.getVersionId());
        wflSteppage.setStepId(flowInstanceInfo.getStepId());
        List<WflSteppage> pageList = wflSteppageService.selectWflSteppageList(wflSteppage);
        /**查询当前节点审批权限*/
        List<WflApprauthor> appAuthorList = wflApprauthorService.selectStepApprAuthorList(flowInstanceInfo.getVersionId(), flowInstanceInfo.getStepId());
        flowInstanceInfo.setPageList(pageList);
        flowInstanceInfo.setAppAuthorList(appAuthorList);
        return ResponseModel.okToJSON(flowInstanceInfo);
    }

    /**
     * @description：电子名片-任务-提交待办任务
     * @author：yjs
     * @date：2024/7/24 11:25
     */
    @ApiOperation(value = "电子名片-任务-提交待办任务", notes = "电子名片-任务-提交待办任务")
    @PostMapping("/submitTask")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel submitTask(@RequestBody FlowInstanceInfo flowInstanceInfo) {
        String salt = getSalt();//盐值
        //获取当前用户的信息
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
        SysUser sysUser = userService.selectUserById(userInfo.getUserId(), salt);
        try {
            AjaxResult result = businessFlowService.submitTask(flowInstanceInfo.getVersionId(), flowInstanceInfo.getInstanceId(),
                    flowInstanceInfo.getStepId(), flowInstanceInfo.getTaskId(), flowInstanceInfo.getKeyInfo(), flowInstanceInfo.getApproveType(),
                    flowInstanceInfo.getApproveMemo(), sysUser, "", salt);
            if (!"0".equals(result.get("code").toString())) {
                return ResponseModel.error("提交待办任务失败," + result.get("msg"));
            }
            /**
             * 2024年10月11日10:25:36 yjs
             * 判断流程是否结束，流程审批结束后需要处理对应的业务数据，当前只有电子名片删除走流程，后续新增其他流程需要修改
             */
            if ("同意提交成功".equals(result.get("msg").toString())) {
                /**
                 * keyInfo内数据说明：
                 * busiId:业务编号
                 * cname:客户名称
                 * busiType:业务类型，busiType  1-商户信息，2-企业信息，3-企业楼宇（厂区），4-个人信息，5-个人网格，6.-农业主体信息
                 * 7-商户信息，8-企业信息，9-个人信息，10.-新型农业主体，11-行业客户删除，12-社团组织删除
                 */
                JSONObject jsonObject = JSONObject.parseObject(flowInstanceInfo.getKeyInfo());
                /**
                 * 1、判断业务类型
                 * 2、根据业务ID删除/停用
                 */
                Long busiId = jsonObject.getLong("busiId");//商户信息的主键id
                switch (jsonObject.getString("busiType")) {
                    case "1":
                        //商户信息删除/停用
                        ecardMerchantInfoService.changeMerchantStatus(busiId);
                        break;
                    case "2":
                        //企业信息删除/停用
                        ecardEnterpriseInfoService.changeEnterpriseStatus(busiId);
                        break;
                    case "3":
                        //企业楼宇（厂区）删除/停用
                        enterpriseLocationService.changeLocationStatus(busiId);
                        break;
                    case "4":
                        //个人信息删除/停用
                        ecardPersonInfoService.changePersonStatus(busiId);
                        break;
                    case "5":
                        //个人网格删除/停用
                        ecardPersonAreaService.changePersonAreaStatus(busiId);
                        break;
                    case "6":
                        //农业主体信息删除/停用
                        ecardAgricultureInfoService.changeAgricultureStatus(busiId);
                        break;
                    case "7":
                        //个体工商户停用/任务停用
                        ecardApiMerchantImportTaskService.closeMerchantImportTask(busiId);
                        break;
                    case "8":
                        //企业停用/任务停用
                        break;
                    case "9":
                        //个人停用/任务停用
                        break;
                    case "10":
                        //新型农业主体停用/任务停用
                        break;
                    case "11":
                        //行业客户删除/停用
                        ecardApiCustomerGroupMerchantService.changeIndustrialCustomerStatus(busiId);
                        break;
                    case "12":
                        //社团组织删除/停用
                        ecardApiCustomerGroupOrganizeService.changeOrganizeStatus(busiId);
                        break;
                     default:
                         break;
                }
            }
            return ResponseModel.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseModel.error("提交待办任务失败！");
        }
    }

    /**
     * @description：电子名片-任务-获取下一节点审批人
     * @author：yjs
     * @date：2024/7/24 11:25
     */
    @ApiOperation(value = "电子名片-任务-获取下一节点审批人", notes = "APP-任务-获取下一节点审批人")
    @PostMapping("/selectApproveUserList")
    @ResponseBody
    @RsaRequest
    public ResponseModel selectApproveUserList(@RequestBody FlowInstanceInfo flowInstanceInfo) {
        String salt = getSalt();//盐值
        //获取当前用户的信息
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
        SysUser sysUser = userService.selectUserById(userInfo.getUserId(), salt);

        WflFlowstep wflFlowstep = new WflFlowstep();
        wflFlowstep.setVersionId(flowInstanceInfo.getVersionId());
        wflFlowstep.setStepId(flowInstanceInfo.getStepId());
        List<WflFlowstep> wflFlowStepList = wflFlowStepService.selectWflFlowstepList(wflFlowstep);
        /**查询下一节点信息*/
        WflFlowstep nextStep = businessFlowService.getNextStepInfo(flowInstanceInfo.getVersionId(), wflFlowStepList.get(0).getOrderNum(), flowInstanceInfo.getInstanceId(), flowInstanceInfo.getKeyInfo());
        /**查询下一节点审批用户*/
        List<SysUser> userList = businessFlowService.getApproveUserList(flowInstanceInfo.getInstanceId(), nextStep, sysUser, "", salt);
        Map<String, Object> data = new HashMap<>();
        //审批人
        data.put("userList", userList);
        //审批人数
        data.put("approvePop", nextStep.getApprovPop());
        data.put("stepName", nextStep.getStepName());
        return ResponseModel.okToJSON(data);
    }

    /**
     * @description：电子名片-任务-流程审批记录列表
     * @author：yjs
     * @date：2024/7/24 11:25
     */
    @ApiOperation(value = "电子名片-任务-流程审批记录列表", notes = "电子名片-任务-流程审批记录列表")
    @ApiImplicitParam(name = "instanceId", value = "流程实例ID", dataType = "String", dataTypeClass = String.class)
    @PostMapping("/approveList")
    @ResponseBody
    @RsaRequest
    public ResponseModel approveList(@RequestBody String json) {
        String instanceId = JSONObject.parseObject(json).getString("instanceId");
        BusiflInstStep busiflInstStep = new BusiflInstStep();
        busiflInstStep.setInstanceId(instanceId);
        List<BusiflInstStep> instStepList = busiflInstStepService.selectBusiflInstApproveList(busiflInstStep);
        return ResponseModel.okToJSONArray(instStepList);
    }

    /**
     * @description：电子名片-任务-流程审批待处理列表
     * @author：yjs
     * @date：2024/7/24 11:25
     */
    @ApiOperation(value = "电子名片-任务-流程审批待处理列表", notes = "电子名片-任务-流程审批待处理列表")
    @PostMapping("/getWaitdoList")
    @ResponseBody
    @RsaRequest
    public ResponseModel getWaitdoList(@RequestBody String json) {
        String salt = getSalt();//盐值
        JSONObject jsonObject = JSONObject.parseObject(json);
        int pageNum = jsonObject.getInteger("pageNum");
        int pageSize = jsonObject.getInteger("pageSize");
        BusiflWaitTask busiflWaitTask = new BusiflWaitTask();
        //获取当前用户的信息
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
        busiflWaitTask.setSts("1");
        busiflWaitTask.setBelongTo(userInfo.getUserId());
        PageHelper.startPage(pageNum, pageSize);
        List<BusiflWaitTask> list = busiflWaitTaskService.selectBusiflWaitTaskList(busiflWaitTask);
        PageInfo pageInfo = new PageInfo(list);
        return ResponseModel.okToJSONArray(pageInfo.getTotal(), list);

    }

    /**
     * @description：电子名片-任务-流程审批已提交列表
     * @author：yjs
     * @date：2024/7/24 11:25
     */
    @ApiOperation(value = "电子名片-任务-流程审批已提交列表", notes = "电子名片-任务-流程审批已提交列表")
    @PostMapping("/hasSubmitList")
    @ResponseBody
    @RsaRequest
    public ResponseModel hasSubmitList(@RequestBody String json) {
        String salt = getSalt();//盐值
        JSONObject jsonObject = JSONObject.parseObject(json);
        int pageNum = jsonObject.getInteger("pageNum");
        int pageSize = jsonObject.getInteger("pageSize");
        BusiflWaitTask busiflWaitTask = JSONObject.parseObject(json, BusiflWaitTask.class);
        //获取当前用户的信息
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
        busiflWaitTask.setPerformer(userInfo.getUserId());
        PageHelper.startPage(pageNum, pageSize);
        List<BusiflWaitTask> list = busiflWaitTaskService.selectHasSubmitTaskList(busiflWaitTask);
        PageInfo pageInfo = new PageInfo(list);
        return ResponseModel.okToJSONArray(pageInfo.getTotal(), list);
    }


    /**
     * @description：电子名片-任务-流程审批已结束列表
     * @author：yjs
     * @date：2024/7/24 11:25
     */
    @ApiOperation(value = "电子名片-任务-流程审批已结束列表", notes = "电子名片-任务-流程审批已结束列表")
    @PostMapping("/closedTaskList")
    @ResponseBody
    @RsaRequest
    public ResponseModel closedTaskList(@RequestBody String json) {
        String salt = getSalt();//盐值
        JSONObject jsonObject = JSONObject.parseObject(json);
        int pageNum = jsonObject.getInteger("pageNum");
        int pageSize = jsonObject.getInteger("pageSize");
        BusiflWaitTask busiflWaitTask = JSONObject.parseObject(json, BusiflWaitTask.class);
        //获取当前用户的信息
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
        busiflWaitTask.setBelongTo(userInfo.getUserId());
        PageHelper.startPage(pageNum, pageSize);
        List<BusiflWaitTask> list = busiflWaitTaskService.selectCloseTaskList(busiflWaitTask);
        PageInfo pageInfo = new PageInfo(list);
        return ResponseModel.okToJSONArray(pageInfo.getTotal(), list);
    }

    /**
     * @description：流程审批待处理业务数 -角标
     * @author：yjs
     * @date：2024/10/12 16:33
     */
    @PassToken
    @ApiOperation(value = "电子名片-任务-流程审批待处理业务数", notes = "电子名片-任务-流程审批待处理业务数")
    @PostMapping("/getWaitdoNumber")
    @ResponseBody
    public ResponseModel getWaitdoNumber() {
        String salt = getSalt();//盐值
        String currentUserId = getCurrentUserId();
        if (!StringUtil.objIsNullOrEmpty(currentUserId)) {
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            BusiflWaitTask busiflWaitTask = new BusiflWaitTask();
            busiflWaitTask.setSts("1");
            busiflWaitTask.setBelongTo(userInfo.getUserId());
            List<BusiflWaitTask> list = busiflWaitTaskService.selectBusiflWaitTaskList(busiflWaitTask);
            return ResponseModel.ok(list.size());
        } else {
            return ResponseModel.ok(0);
        }
    }

}
